package com.youlu.campus.service.commission;

import com.alibaba.fastjson.JSON;
//import com.ctrip.framework.apollo.Config;
//import com.ctrip.framework.apollo.ConfigService;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.base.user.UserGrade;
import com.youlu.campus.base.user.UserWithdraw;
import com.youlu.campus.entity.SystemApolloConfig;
import com.youlu.campus.entity.commission.*;
import com.youlu.campus.entity.commission.dto.CalCommissionDTO;
import com.youlu.campus.entity.commission.dto.DistributorAccountGradeDTO;
import com.youlu.campus.service.system.SystemApolloConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : [dengbo]
 * @className : DistributorGradeService
 * @description : [分佣比例等级]
 * @createTime : [2023/2/3 15:39]
 */
@Service
@Slf4j
public class DistributorGradeService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private SystemApolloConfigService systemApolloConfigService;

    /**
     * 计算用户佣金金额
     *
     * @param userId              账号ID
     * @param baseCommissionRatio 基础佣金比例
     * @param amount              计算佣金金额
     * @return
     */
    public CalCommissionDTO doCalCommission(String userId, Double baseCommissionRatio, Integer amount) {
        log.info("【佣金计算】userId:{}|baseCommissionRatio:{}|amount:{}", userId, baseCommissionRatio, amount);
        DistributorAccountGradeDTO distributorRateDto = this.getDistributorRate(userId);
        Integer incCommissionRateNum = distributorRateDto.getCommissionRate() < 0 ? 0 : distributorRateDto.getCommissionRate();
        CalCommissionDTO calCommission = new CalCommissionDTO();
        calCommission.setBaseCommissionRatio(baseCommissionRatio);
        calCommission.setIncCommissionRatio(incCommissionRateNum);
        //计算佣金
        calCommission.calSharingCommissionAmount(BigDecimal.valueOf(amount));
        log.info("【佣金计算】end userId:{} 计算结果:{}",
                userId, JSON.toJSONString(calCommission));
        return calCommission;
    }

    /**
     * 获取分账提高比例 单位去掉%的整数
     *
     * @param accountId
     * @return
     */
    public DistributorAccountGradeDTO getDistributorRate(String accountId) {
        DistributorAccountGradeDTO dto = new DistributorAccountGradeDTO();
        // 等级比列
        List<DistributorGrade> gradeList = mongoTemplate.find(new Query(), DistributorGrade.class);
        Query q = new Query();
        q.addCriteria(Criteria.where("accountId").is(accountId));
        DistributorAccount account = mongoTemplate.findOne(q, DistributorAccount.class);
        long totalOrderMoney = account == null ? 0 : account.getTotalOrderMoney();
        gradeList = gradeList.stream().sorted(Comparator.comparing(DistributorGrade::getTotalMoney)).collect(Collectors.toList());
        int size = gradeList.size();
        // 添加开关
//        Config config = ConfigService.getAppConfig();
//        String cnf = config.getProperty("user.grade.gray", "{}");
//        UserGrade userGrade = JSON.parseObject(cnf, UserGrade.class);
        SystemApolloConfig systemApolloConfig = systemApolloConfigService.find();
        UserGrade userGrade=systemApolloConfig.getUserGrade();
        if (userGrade.getOpened() && size > 0 && userGrade.getUserList().contains(accountId)) {
            DistributorGrade maxGrade = gradeList.get(size - 1);
            dto.setGradeName(maxGrade.getName());
            dto.setTotalMoney(maxGrade.getTotalMoney());
            dto.setCommissionRate(maxGrade.getCommissionRate());
            return dto;
        }
        for (int i = 0; i < size; i++) {
            int next = i + 1;
            DistributorGrade s = gradeList.get(i);
            if (next <= size - 1) {
                DistributorGrade n = gradeList.get(next);
                if (totalOrderMoney >= s.getTotalMoney() && totalOrderMoney < n.getTotalMoney()) {
                    dto.setGradeName(s.getName());
                    dto.setTotalMoney(s.getTotalMoney());
                    dto.setCommissionRate(s.getCommissionRate());
                    return dto;
                }
                continue;
            }
            dto.setGradeName(s.getName());
            dto.setTotalMoney(s.getTotalMoney());
            dto.setCommissionRate(s.getCommissionRate());
            return dto;
        }
        dto.setGradeName("");
        dto.setTotalMoney(0L);
        dto.setCommissionRate(0);
        return dto;
    }
}
